//上传图片模板
const multer = require("multer");
const path = require("path");
const fs = require("fs");

//打开或创建名为public的文件夹
const createFolder = (folder) => {
  try {
    fs.accessSync(folder); //打开文件夹
  } catch (err) {
    fs.mkdirSync(folder); //创建文件夹
  }
};

const uploadFolder = "./public/"; //设定存储文件夹为file - serve下的public文件夹;
createFolder(uploadFolder);

//define stroage for the images
const storage = multer.diskStorage({
  //destination for files
  destination: (req, file, cb) => {
    cb(null, uploadFolder);
  },
  //add back the extension
  filename: (req, file, cb) => {
    //console.log("最开始", file);
    cb(null, Date.now() + path.extname(file.originalname));
  },
});

const fileFilter = (req, file, cb) => {
  const extension = file.mimetype.split("/")[0];
  if (
    extension !== "video" &&
    extension !== "image" &&
    extension !== "audio" &&
    extension !== "application"
  ) {
    return cb(null, false);
  }
  cb(null, true);
  // if (
  //   file.mimetype === "image/png" ||
  //   file.mimetype === "image/jpg" ||
  //   file.mimetype === "image/jpeg"
  // ) {
  //   cb(null, true);
  // } else {
  //   console.log("tttttttt", req);
  //   cb(null, false);
  // }
};

//upload parameters for multer
const upload = multer({ storage: storage, fileFilter: fileFilter });
module.exports = { upload };
